package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.ExListener.ExLin;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author DongYu Zhou
 * @date 2022/6/21 10:03
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private ExLin exLin;

    @Override
    @Cacheable(value = "dict",key = "'selectIndexList'+#id")
    public List<Dict> findChildData(Long id) {
        //1. 根据传入的 id => parent_id 查询 dict => name
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = dictMapper.selectList(wrapper);

        //2. 判断是否有子节点
        for (Dict dict : dictList) {
            Long id1 = dict.getId();
            boolean children = this.isChildren(id1);
            dict.setHasChildren(children);
        }
        return dictList;
    }

    //判断是否有子节点
    private boolean isChildren(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Long aLong = dictMapper.selectCount(wrapper);
        return aLong > 0;
    }

    //导出数据
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1设置response基础参数
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //2.查询字典表所有数据
            List<Dict> dictList = dictMapper.selectList(null);

            //3. 转换为vo
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            //4. 调用easyEx工具生成文档
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importData(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream,DictEeVo.class,exLin)
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw  new YyghException(20001,"导入失败");
        }
    }

    //查询数据字典数据  两种->自定义数据 || 国标数据
    @Override
    public String getName(String parentDictCode, String value) {

        if (StringUtils.isEmpty(parentDictCode)){
            //就是国标数据
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(wrapper);
            if (dict!=null){
                return dict.getName();
            }
        }else {
            //就是自定义数据
            //查询父级别的数据parentDictCode
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", parentDictCode));

            //根据parent_id和value确认唯一数据
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value).eq("parent_id",dict.getId());
            Dict dict1 = dictMapper.selectOne(wrapper);
            if (dict1!=null){
                return dict1.getName();
            }
        }
        return "";
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        List<Dict> list = baseMapper.selectList(
                new QueryWrapper<Dict>()
                        .eq("parent_id", dict.getId())
        );
        return list;
    }



}
